package cn.edu.sjtu.process_management.service;

import cn.edu.sjtu.process_management.model.OperatorSet;
import cn.edu.sjtu.process_management.model.User;
import cn.edu.sjtu.process_management.repository.OperatorSetRepository;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import org.springframework.core.io.Resource;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MessageService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OperatorSetRepository operatorSetRepository;
    @Value("${microServiceManagement.userFind.url}")
    private String userFindUrl; // 微服务管理平台提供的user查询接口
    @Value("${microServiceManagement.messageSend.url}")
    private String messageSendUrl;

    public void sendMessage(User user, JSONArray toUserList, JSONObject message) {
        //根据ecnId查询toUser
        //构建请求体
        message.put("fromUser", user);
        message.put("toUser", toUserList);
        //发送该信息
        restTemplate.postForEntity(messageSendUrl, message, JSONObject.class);
    }

    //根据userId查询user详细信息
    public User getUserByUserId(String userId) {
        JSONObject object = restTemplate.getForObject(userFindUrl + "?userId=" + userId, JSONObject.class);
        JSONArray data = object.getJSONArray("data");
        return data.getObject(0, User.class);
    }

    public JSONArray getUserByECN(String ecnId) {
        List<OperatorSet> operatorSetList = operatorSetRepository.findByInstanceIdList(ecnId);
        List<User> users = operatorSetList.stream().map(operatorSet -> getUserByUserId(operatorSet.getUserId())).collect(Collectors.toList());
        return JSONArray.parseArray(JSON.toJSONString(users));
    }

    public JSONArray getUserByRole(int role) {
        JSONObject object = restTemplate.getForObject(userFindUrl + "?role=" + role, JSONObject.class);
        return object.getJSONArray("data");
    }
}
